<template>
    <div>
        <el-card>
            <el-alert type="info" show-icon :title='setTitle+"商品信息"' center :closable='false'></el-alert>
            <el-steps :active="activeTabs - 0" align-center finish-status="finish">
                <el-step v-for="(item, index) in processTitle" :key="index" :title="item"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <el-form label-position="top" :model='addForm' :rules='addFormRules' ref="addFormRef">
                <el-tabs tab-position="left" v-model="activeTabs" :before-leave='beforeTabLeave' @tab-click="tabClicked">
                    <el-tab-pane name="0" label="基本参数">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input placeholder="请新增商品名称" v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="price">
                            <el-input placeholder="请新增商品价格" v-model="addForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="weight">
                            <el-input placeholder="请新增商品重量" v-model="addForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="number">
                            <el-input placeholder="请新增商品数量" v-model="addForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader 
                            expand-trigger='hover' 
                            :options='categories' 
                            :props='cateProps' 
                            placeholder="请选择商品的分类" 
                            v-model="addForm.goods_cat"
                            @change="handelChange"></el-cascader>
                        </el-form-item>
                        <!-- <el-button type="primary" class="addBtn" @click="addCategories" v-if="tabPaneVisible">修改商品</el-button> -->
                    </el-tab-pane>
                    <el-tab-pane name="1" label="商品参数">
                        <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox v-for="(value, index) in item.attr_vals" :key="index" :label="value" border></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="2" label="商品属性"> 
                        <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="3" label="商品图片">
                        <el-upload
                        :action="uploadUrl"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        list-type="picture"
                        :headers="headerObj"
                        :on-success="handleSuccess">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane name="4" label="商品内容">
                        <quill-editor v-model="addForm.goods_introduce" />
                        <el-button type="primary" class="addBtn" @click="addCategories">{{setTitle}}商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>

        <el-dialog :visible.sync="priviewDialogVisible" width="60%" :before-close="priviewClose">
            <img :src="priviewPath" class="priviewImg">
        </el-dialog>
    </div>
</template>

<script>
    import _ from 'lodash'

    export default {
        data() {
            return {
                activeTabs: 0,
                processTitle: [
                    '基本参数',
                    '商品参数',
                    '商品属性',
                    '商品图片',
                    '商品内容'
                ],

                categories          : [],
                manyTableData       : [],
                onlyTableData       : [],

                cateProps: {
                    label           : 'cat_name',
                    value           : 'cat_id',
                    children        : 'children'
                },

                addForm: {
                    goods_name      : '',
                    goods_price     : 0,
                    goods_weight    : 0,
                    goods_number    : 0,
                    goods_cat       : [],
                    goods_introduce : '',
                    pics            : [],
                    attrs           : []
                },
                addFormRules: {
                    goods_name      : [{ required: true, message: '请填写商品名称', trigger: 'blur' }],
                    goods_price     : [{ required: true, message: '请填写商品价格', trigger: 'blur' }],
                    goods_weight    : [{ required: true, message: '请填写商品重量', trigger: 'blur' }],
                    goods_number    : [{ required: true, message: '请填写商品数量', trigger: 'blur' }],
                    goods_cat       : [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
                },
                
                uploadUrl: 'https://www.dapmix.top/api/upload',
                headerObj: {
                    Authorization: window.sessionStorage.getItem('token')
                },
                priviewPath: '',
                priviewDialogVisible: false,

                setTitle: '添加',
                routeRow: {}
            }
        },
        
        created() {
            this.getCategories()
            // console.log(this.$route.params)
            // console.log(this.routeRow)
            if (this.$route.params.row) {
                this.setTitle = '编辑'
                this.routeRow = this.$route.params.row
                this.getGoodsInfo()
            }
        },

        methods: {
            async getCategories() {
                const { data: res } = await this.$http.get('categories')
                if (res.meta.status == 200) {
                    this.categories = res.data
                } else {
                    this.$message.error('获取商品列表失败')
                }
            },
            async getClassList(setSel) {
                const { data: res } = await this.$http.get(`categories/${this.cateID}/attributes`, { params: { sel: setSel } })
                if (res.meta.status == 200) {
                    if (setSel == 'many') {
                        res.data.forEach(item => {
                            item.attr_vals = item.attr_vals.length > 0 ? item.attr_vals.split(',') : []
                        })
                    }
                    setSel == 'many' ? this.manyTableData = res.data : this.onlyTableData = res.data
                } else {
                    this.$message.error(`获取${this.checkSel(setSel)}数据失败`)
                }
            },
            
            handelChange() {
                if (this.addForm.goods_cat.length < 3) {
                    this.$message.error('商品分类只允许选中第三级分类')
                    this.addForm.goods_cat = []
                }
            },

            // 切换tab条件
            beforeTabLeave (activeName, oldActiveName) {
                if (oldActiveName == 0 && this.addForm.goods_cat < 3) {
                    this.$message.error('请先选择商品分类')
                    return false
                }
            },

            // upload bind event
            handlePreview(file) {
                this.priviewPath = 'https://www.dapmix.top/temp/' + file.response.data.tmp_path
                this.priviewDialogVisible = true
            },
            handleSuccess(response) {
                // console.log(response)
                const picInfo = { pic: response.data.tmp_path }
                this.addForm.pics.push(picInfo)
            },
            handleRemove(file) {
                const filePath = file.response.data.tmp_path
                const index =  this.addForm.pics.findIndex(res => res.pic == filePath)
                this.addForm.pics.splice(index, 1)
            },
            priviewClose() {
                this.priviewPath = ''
                this.priviewDialogVisible = false
            },

            tabClicked() {
                if (!this.$route.params.row) {
                    switch (this.activeTabs) {
                        case '1': 
                            this.getClassList('many')
                            break
                        case '2':
                            this.getClassList('only')
                            break
                    }
                } else {
                    // this.showClassList()
                }
            },

            addCategories() {
                this.$refs.addFormRef.validate(valid => {
                    if (!valid) {
                        this.$message.error('尚有必填项未被填写')
                    } else {
                        const submitData = _.cloneDeep(this.addForm)
                        submitData.goods_cat = submitData.goods_cat.join(',')
                        this.addForm.attrs = []
                        this.manyTableData.forEach(item => {
                            const itemData = {
                                attr_id     : item.attr_id,
                                attr_value  : item.attr_vals.join(',')
                            }
                            this.addForm.attrs.push(itemData)
                        })
                        this.onlyTableData.forEach(item => {
                            const itemData = {
                                attr_id     :item.attr_id,
                                attr_value  :item.attr_vals
                            }
                            this.addForm.attrs.push(itemData)
                        })
                        submitData.attrs = this.addForm.attrs
                        if (this.setTitle == '添加') {
                            this.addGoods(submitData)
                        } else {
                            this.editGoods(submitData)
                        }
                    }
                })
            },

            async addGoods(goodsData) {
                const { data: res } = await this.$http.post('goods', goodsData)
                console.log(res)
                if (res.meta.status == 201) {
                    this.$message.success('添加商品成功')
                    this.$router.push('/goods')
                } else {
                    this.$message.error('添加商品失败')
                }
            },

            async getGoodsInfo() {
                const { data: res } = await this.$http.get(`goods/${this.routeRow.goods_id}`)
                if (res.meta.status == 200) {
                    this.addForm = res.data
                    this.updateFormData(this.addForm)
                    console.log(this.addForm)
                } else {
                    this.$message.error('获取商品信息失败')
                }
            },
            updateFormData() {
                // 更新goods_cat
                const form_cat = this.addForm.goods_cat.split(',')
                this.addForm.goods_cat = []
                form_cat.forEach(item => {
                    this.addForm.goods_cat.push(Number(item))
                })
                this.showClassList()
            },
            async editGoods(form) {
                const { data: res } = await this.$http.put(`goods/${this.routeRow.goods_id}`, form)
                if (res.meta.status == 200) {
                    this.$message.success('更新商品数据成功')
                    this.$router.push('/goods')
                } else {
                    this.$message.error('更新商品数据失败')
                }
            },
            // 编辑状态分配many和only参数
            showClassList() {
                const manySession = []
                const onlySession = []
                this.addForm.attrs.forEach(item => {
                    if (item.attr_sel == 'many') {
                        item.attr_vals = item.attr_value.length > 0 ? item.attr_value.split(',') : []
                        manySession.push(item)
                    } else {
                        onlySession.push(item)
                    }
                })
                this.manyTableData = manySession
                this.onlyTableData = onlySession
            }
        },

        computed: {
            cateID() {
                if (this.addForm.goods_cat.length > 2) {
                    return this.addForm.goods_cat[2]
                } else {
                    return null
                }
            },
            checkSel(sel) {
                return sel == 'many' ? '动态参数' : '静态属性'
            }
        }
    }
</script>

<style lang="less" scoped>
    .el-tabs{
        margin-top: 2rem;
    }
    .el-tab-pane{
        padding-left: 1rem;
    }
    .el-cascader{
        width: 100%;
    }
    .el-checkbox{
        margin: 0 1rem 0 0 !important;
    }
    .priviewImg{
        width: 100%;
    }
    .addBtn{
        margin-top: 1rem;
    }
</style>